package inv.stask.beans;

import inv.stask.logic.TaskUtil;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.SortedSet;

public class Task implements Serializable{

	private static final long serialVersionUID = 6335122418813919083L;
	
	private Integer id;
	private String name;
	private Priority priority;
	private Boolean done;
	private int postponed;
	private Date lastChange;
	private Date dueDate;
	
	private SortedSet<Tags> taglist;
	
	public enum Priority{
		LOW("low"), NORMAL("normal"), HIGH("high");
		String value;
		Priority(String value){
			this.value = value;
		}
		
		@Override
		public String toString() {
			return value;
		}
		
		public Priority byString(String value){
			for(Priority p: values()){
				if(p.value.equals(value))
					return p;
			}
			
			return null;
		}
	};
	
	
	
	public Task() {
		lastChange	= new Date();
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public Date getDueDate() {
		return dueDate;
	}

	public void setDueDate(Date dueDate) {
		Date today	= TaskUtil.getToday();
		Date lastModif = getLastChange();
		
		if(TaskUtil.date_yyyyMMdd_equals(today, lastModif))
			if(this.dueDate != null && dueDate != null && this.dueDate.compareTo(dueDate) > 0 
					&& !TaskUtil.date_yyyyMMdd_equals(this.dueDate, dueDate)){
				this.lastChange	= today;
				incPostponed();
			}
		
		this.dueDate = dueDate;
	}
	
	public static Task newTask(String name){
		Task task	= new Task();
		task.setName(name);
		Calendar cal 	= Calendar.getInstance();
		cal.add(Calendar.WEEK_OF_YEAR, 1);
		
		task.setDueDate(cal.getTime());
		task.setPriority(Priority.NORMAL);
		task.setDone(false);
		
		return task;
	}
	
	public static Task newTask(){
		return newTask("--- task name ---");
	}

	public Priority getPriority() {
		return priority;
	}

	public void setPriority(Priority priority) {
		this.priority = priority;
	}

	public Boolean getDone() {
		return done;
	}

	public void setDone(Boolean done) {
		this.done = done;
	}

	protected void incPostponed() {
		this.postponed ++;
	}

	public Integer getPostponed() {
		return postponed;
	}

	public Date getLastChange() {
		return lastChange;
	}
	
	public String getTagListAsString(){
		return Tags.exportToString(this.getTaglist());
	}
	
	public void setTaglist(SortedSet<Tags> taglist) {
		this.taglist = taglist;
	}
	
	public SortedSet<Tags> getTaglist() {
		return taglist;
	}
	
}
